<template>
  <div class="app-container">
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="70%"
      @close="cancel"
    >
      <el-form
        ref="dataFormRef"
        :model="formData"
        :rules="dataFormRules"
        :disabled="isDisabled"
        label-width="80px"
      >
        <div>
          <h3>基本信息</h3>
          <el-form-item label="拼团名称" prop="name" style="width: 480px">
            <el-input v-model="formData.name" placeholder="请输入拼团名称" />
          </el-form-item>

          <el-form-item label="活动时间" prop="activityTimes">
            <div class="block">
              <el-date-picker
                v-model="activityTimes"
                type="datetimerange"
                range-separator="至"
                start-placeholder="请选择"
                end-placeholder="请选择"
              />
            </div>
          </el-form-item>

          <el-form-item label="成团期限" prop="limitHours">
            <el-input
              v-model="formData.limitHours"
              type="number"
              min="1"
              max="24"
              oninput="value=value.replace(/[^\d]+/g,'')"
              style="width: 200px"
            >
              <template #append>小时</template>
            </el-input>
          </el-form-item>
          <el-form-item label="参团人数" prop="limitMembers">
            <el-input
              v-model="formData.limitMembers"
              type="number"
              min="2"
              max="8"
              oninput="value=value.replace(/[^\d]+/g,'')"
              style="width: 200px"
            >
              <template #append>人</template>
            </el-input>
          </el-form-item>
        </div>

        <div class="discount">
          <h3>商品及优惠</h3>
          <el-form-item prop="actProdSkuList" label="活动商品">
            <el-button
              v-hasPerm="['act:festival:edit']"
              type="primary"
              link
              size="small"
              class="text"
              @click="selectionProducts"
              >选择商品</el-button
            >

            <el-table
              highlight-current-row
              :data="formData.actProdSkuList"
              class="skuTable"
            >
              <!-- 自定义暂无数据 -->
              <template #empty>
                <div style="height: 92px; line-height: 92px">暂无数据</div>
              </template>

              <el-table-column label="商品名称" prop="name" align="center">
              </el-table-column>

              <el-table-column label="商品规格" prop="attribute" align="center">
                <template #default="{ row }">
                  <span>{{ mergingAttributeValue(row.attribute) }}</span>
                </template>
              </el-table-column>

              <el-table-column
                label="供货价"
                prop="supplierPrice"
                align="center"
              >
              </el-table-column>

              <el-table-column label="销售价" prop="salePrice" align="center">
              </el-table-column>

              <el-table-column
                label="参考价"
                prop="referencePrice"
                align="center"
              >
              </el-table-column>

              <el-table-column label="活动价" prop="actPrice" align="center">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'actProdSkuList.' + $index + '.actPrice'"
                    :rules="actSkuRules.actPrice"
                  >
                    <!-- <el-input v-model="row.actPrice" placeholder="请输入" /> -->
                    <el-input
                      v-model="formData.actProdSkuList![$index].actPrice"
                      min="0.01"
                      oninput="value=value.replace(/[^\d.]+/g,'').replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3') + '' "
                      placeholder="请输入"
                    />
                  </el-form-item>
                </template>
              </el-table-column>

              <el-table-column label="库存" prop="remained" align="center">
              </el-table-column>

              <el-table-column label="活动库存" prop="actStore" align="center">
                <template #default="{ row, $index }">
                  <el-form-item
                    :prop="'actProdSkuList.' + $index + '.actStore'"
                    :rules="actSkuRules.actStore"
                  >
                    <el-input
                      v-model="row.actStore"
                      placeholder="请输入"
                      min="1"
                      oninput="value=parseInt(value.replace(/[^\d]+/g,''))"
                    ></el-input>
                  </el-form-item>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </div>

        <div>
          <h3>其他设置</h3>
          <el-form-item label="每人限购" prop="limitBuyTimes">
            <el-input
              v-model="formData.limitBuyTimes"
              placeholder="请输入限购次数"
              type="number"
              min="0"
              oninput="value=value.replace(/[^\d]+/g,'')"
              style="width: 200px"
            >
              <template #append>件</template>
            </el-input>
          </el-form-item>
          <el-form-item label="自动成团" prop="autoGroup">
            <el-checkbox
              v-model="formData.autoGroup"
              label="到期后自动成团"
              size="large"
            />
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取 消</el-button>
          <el-button type="primary" @click="handleSubmission">确 定</el-button>
        </div>
      </template>
    </el-dialog>

    <chooseProduct ref="chooseProductRef" @confirm="updateActSkuList" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "AddOrEditGroupActivity",
  inheritAttrs: false,
});

defineExpose({
  openAddDialog,
  openEditDialog,
});

import {
  GroupTypeForm,
  GroupSkuListVO,
  SkuVO,
  GroupActProdSku,
} from "@/api/group/types";
import { formatDate } from "@/utils/dateUtils";
import chooseProduct from "@/views/marketing/group/chooseProduct.vue";
import {
  getSkuInfoListByIds,
  addGroupActivity,
  getGroupInfoById,
  updateGroupActivity,
} from "@/api/group/index";

const dataFormRef = ref(ElForm);
const chooseProductRef = ref();
let isDisabled = ref<boolean>(false);

const dialog = reactive<DialogOption>({
  title: "新增活动",
  visible: false,
});

let formData = reactive<GroupTypeForm>({
  id: undefined,
  name: "",
  startTime: "",
  endTime: "",
  limitHours: undefined,
  limitMembers: undefined,
  limitBuyTimes: undefined, //0代表不限次数, 默认 0
  autoGroup: true,
  actProdSkuList: [],
});
let selectId = ref<number[]>();
let activityTimes = ref<[Date | undefined, Date | undefined]>();

//自定义校验规则
const validateActivityTimes = (rule: any, value: any, callback: any) => {
  let startDate = activityTimes.value?.[0];
  if (startDate) {
    //非编辑时, 才需要校验 开始时间 - 当前时间, 必须大于等于10分钟
    if (!formData.id) {
      let valid =
        parseInt(String(startDate.getTime() - new Date().getTime())) >=
        60 * 10 * 1000;
      if (!valid) {
        callback(new Error("开始时间 - 当前时间, 必须大于等于10分钟!"));
      }
    }

    callback();
  } else {
    callback(new Error("请选择活动时间!"));
  }
};

const validateLimitBuyTimes = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请填写限购次数!"));
  }

  if (value > 100) {
    callback(new Error("限购次数, 必须小于等于100!"));
  }

  callback();
};

const validateLimitMembers = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请填写参团人数!"));
  }

  if (!(value > 0 && value <= 8)) {
    callback(new Error("参团人数, 必须大于 0 并且 小于等于 8 !"));
  }

  callback();
};

const validateLimitHours = (rule: any, value: any, callback: any) => {
  if (!value) {
    callback(new Error("请填写成团期限!"));
  }

  if (!(value > 0 && value <= 24)) {
    callback(new Error("成团期限, 必须大于 0 并且 小于等于 24 !"));
  }

  callback();
};

const dataFormRules = reactive({
  name: [
    { required: true, message: "请输入活动名称", trigger: "blur" },
    { max: 15, message: "最大长度不能超过15!", trigger: "blur" },
    { min: 4, message: "最小长度不能小于4!", trigger: "blur" },
  ],
  activityTimes: [
    { required: true, validator: validateActivityTimes, trigger: "blur" },
  ],
  limitBuyTimes: [
    { required: true, validator: validateLimitBuyTimes, trigger: "blur" },
  ],
  limitMembers: [
    { required: true, validator: validateLimitMembers, trigger: "blur" },
  ],
  limitHours: [
    { required: true, validator: validateLimitHours, trigger: "blur" },
  ],
});

const actSkuRules = reactive({
  actPrice: [{ required: true, message: "请输入活动价", trigger: "change" }],
  actStore: [{ required: true, message: "请输入活动库存", trigger: "change" }],
});

// 新增
function openAddDialog() {
  dialog.title = "新增活动";
  isDisabled.value = false;
  dialog.visible = true;
}

//修改
function openEditDialog(id: number, isDisable: boolean) {
  dialog.title = "编辑活动";
  isDisabled.value = isDisable;
  getGroupInfoById(id).then(({ data }) => {
    // console.log(data);
    // formData = data; //会导致input输入不立刻生效
    Object.assign(formData, data);

    //回显日期选择
    activityTimes.value = [
      new Date(formData.startTime),
      new Date(formData.endTime),
    ];
    dialog.visible = true;
  });
}

function cancel() {
  resetForm();
  dialog.visible = false;
}

/** 重置表单 */
function resetForm() {
  dataFormRef.value.resetFields();
  dataFormRef.value.clearValidate();

  Object.assign(formData, {
    id: undefined,
    name: "",
    startTime: "",
    endTime: "",
    limitHours: undefined,
    limitMembers: undefined,
    limitBuyTimes: undefined, //0代表不限次数, 默认 0
    autoGroup: true,
    actProdSkuList: [],
  });

  activityTimes.value = [undefined, undefined];
}

function selectionProducts() {
  selectId.value = formData.actProdSkuList!.map((actSku) => actSku.skuId);

  // console.log("父 : " + selectId.value);

  chooseProductRef.value.open(selectId.value);
}

function updateActSkuList(ids: number[]) {
  // console.log(formData.actProdSkuList);

  //0.根据sku的ids获取对应的sku信息
  if (ids.length > 0) {
    getSkuInfoListByIds(ids).then(({ data }) => {
      //1.添加新的sku
      let selectedSkuList = data.list;

      // //fixme 因为目前getSkuInfoListByIds返回的是mock数据, 所以无论如何都会返回 5 条写死的sku, 这里自己再根据 ids 过滤下
      // selectedSkuList = selectedSkuList.filter((item) =>
      //   ids.find((id) => id == item.id)
      // );

      selectedSkuList.forEach((sku) => {
        let doesItExist = formData.actProdSkuList?.some((actSku) => {
          return actSku.skuId == sku.id;
        });
        if (!doesItExist) {
          let actSku: GroupActProdSku = {
            actPrice: 0,
            actStore: 0,
            skuId: sku.id,
            ...sku,
          };

          //清除id, 因为上面的 ...sku 把id (skuId) 给错了 actSku.id
          actSku.id = undefined;

          formData.actProdSkuList?.push(actSku);
        }
      });

      //2.过滤移除的sku
      formData.actProdSkuList = formData.actProdSkuList?.filter((actSku) => {
        return selectedSkuList.some((sku) => sku.id == actSku.skuId);
      });
    });
  } else {
    formData.actProdSkuList = [];
  }
}

//合并sku属性值
function mergingAttributeValue(AttributeValueStr: any) {
  let AttributeValueList = JSON.parse(AttributeValueStr);
  let valueArr = [];
  for (let i = 0; i < AttributeValueList.length; i++) {
    const item = AttributeValueList[i];
    valueArr.push(Object.values(item));
  }
  return valueArr.join(",");
}

//新增,修改
function handleSubmission() {
  dataFormRef.value.validate((isValid: boolean) => {
    if (isValid) {
      formData.startTime = formatDate(
        activityTimes.value?.[0],
        "YYYY-mm-dd HH:MM:SS"
      );

      formData.endTime = formatDate(
        activityTimes.value?.[1],
        "YYYY-mm-dd HH:MM:SS"
      );

      // const data = JSON.parse(JSON.stringify(formData.actProdSkuList));
      // console.log(data);

      // const arr = data.map((item: any) => {
      //   return {
      //     actPrice: item.actPrice,
      //     actStore: item.actStore,
      //     skuId: item.skuId,
      //     prodId: item.prodId,
      //   };
      // });

      // formData.actProdSkuList = arr;

      const data = JSON.parse(JSON.stringify(formData));
      data.actProdSkuList = data.actProdSkuList?.map((item: any) => {
        return {
          actPrice: item.actPrice,
          actStore: item.actStore,
          skuId: item.skuId,
          prodId: item.prodId,
          pic: undefined,
          supplierPrice: null,
          salePrice: null,
          referencePrice: null,
          remained: null,
          attribute: [],
        };
      });

      if (data.id) {
        updateGroupActivity(data).then(() => {
          ElMessage.success("修改成功");
          resetForm();
          dialog.visible = false;
        });
      } else {
        addGroupActivity(data).then(() => {
          ElMessage.success("新增成功");

          dialog.visible = false;
          resetForm();
        });
      }
    }
  });
}
</script>

<style lang="scss" scoped>
h3 {
  font-size: 15px;
}

.spacing {
  margin: 0 10px;
}

.discount {
  margin: 60px 0;
}

.text {
  margin: 8px 0;
  font-size: 13px;
}

.skuTable ::v-deep(.el-form-item__error) {
  position: static; //解决Table里无法显示校验错误提示语的问题
}
</style>
